# coding=utf-8
"""
Copyright 2019-2020 Fang Jin Biao

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# @Time    : 2020/7/19 19:16
# @Author  : Fang Jin Biao
# @Email   : 215466914@qq.com
# @File    : devops_service.py
# @Project : SnowAdminWeb
import datetime
import uuid
from collections import OrderedDict

from sqlalchemy import or_

from webapp.config import api_utils
from webapp.dto_mapper import raw_text_fields, app_fields, deploy_fields, deployhistory_fields, database_fields
from webapp.extensions import AppException
from webapp.models import RawText,db
from webapp.tools import format_date, download_excel, connect_server
from flask_restful import marshal

class rawExtractionService:
    @staticmethod
    def query_all(page=1, size=9999, **kwargs) -> list:
        title = kwargs.get('title')
        query = []
        if title:
            query.append(or_(RawText.preparation.like(f'%{title}%'), RawText.characterization.like(f'%{title}%'),
                             RawText.mechanism.like(f'%{title}%')))
        return RawText.query.filter(*query).paginate(int(page), per_page=int(size),
                                                                              error_out=False)
    @staticmethod
    def find_by_id(id: int = None,user_id:str=None) -> RawText:
        data = RawText.query.filter(RawText.article_id == id).one_or_none()
        if data is None:
            raise AppException(f'您所操作的对象已不存在!')
        return data

    @staticmethod
    def download(data_list: list):
        contents = []
        for d in data_list:
            data = OrderedDict()
            data["服务器名称"] = d.name
            data["服务器IP"] = d.ip
            data["端口"] = d.port
            data["账号"] = d.account
            data["创建时间"] = format_date(d.create_time) if d.create_time else ""
            contents.append(data)
        return download_excel(contents)
